//
//  StoreViewController.m
//  MM
//
//  Created by 郑渊文 on 6/1/15.
//  Copyright (c) 2015 王晨辉. All rights reserved.
//

#import "StoreViewController.h"
#import "CommonMacro.h"
#import "PayViewController.h"
#import "DataSigner.h"
#import "Order.h"
#import <AlipaySDK/AlipaySDK.h>


@interface StoreViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSString *numberCount;
    NSString *allPrice;
    UIButton *backBtn;
    UILabel *countLable;
    UILabel *priceLable;
}
@property(nonatomic,copy)NSMutableArray *nameArray;
@property(nonatomic,copy)NSMutableArray *priceArray;
@property(nonatomic,copy)UITableView *myTable;
@end

@implementation StoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
    ////NSLog(@"_statuId是什么啊%@",_statuId);
    _nameArray = [NSMutableArray array];
    _priceArray = [NSMutableArray array];
    NSDictionary *param4 = @{@"babyId":[BabyManager shareInstance].babyId,@"classstatus":_statuId};
    
    [UserDAL getWaitForPayParams:param4 withBlock:^(NSDictionary *data, NSError *error) {
        if (data) {
            ////NSLog(@"what%@",data);
            numberCount =data[@"classCount"];
            allPrice= data[@"totalPrice"];
            NSArray *array = data[@"dataList"];
            for (NSDictionary *mydic in array) {
                [_nameArray addObject:mydic[@"className"]] ;
                [_priceArray addObject:mydic[@"classPrice"]] ;
            }
            [_myTable reloadData];
            
        }else
        {
            
        }
    }];

//    _nameArray = [NSMutableArray arrayWithObjects:@"语文语文语文",@"数学数学数学",@"英语英语英语",@"政治政治政治",@"狗屎狗屎狗屎狗屎", nil];
//    _priceArray = [NSMutableArray arrayWithObjects:@"50",@"50",@"50",@"50",@"50", nil];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

-(void)viewDidAppear:(BOOL)animated
{
      priceLable.text = [NSString stringWithFormat:@"共%@元钱",allPrice];
    countLable.text = [NSString stringWithFormat:@"共%@个课时",numberCount];
}

-(void)initSubViews
{
    
    self.navigationItem.title = @"预约课程";
    
    [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#34bd81" alpha:1]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];

    
    //自定义左右按钮
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setBackgroundImage:[UIImage imageNamed:@"_0000_返回.png"]
     
                      forState:UIControlStateNormal];
    
    [button addTarget:self action:@selector(back)
     
     forControlEvents:UIControlEventTouchUpInside];
    
    button.frame = CGRectMake(0, 0, 20, 15);
    
    
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    
    
    self.navigationItem.leftBarButtonItem = menuButton;
    
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    bgView.backgroundColor = UIColorWithRGBA(240, 239, 245, 1);
    [self.view addSubview:bgView];

    _myTable = [[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    _myTable.delegate = self;
    _myTable.dataSource = self;
    [bgView addSubview:_myTable];
    _myTable.backgroundColor = UIColorWithRGBA(240, 239, 245, 1);
    
    UIView *payView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-150, SCREEN_WIDTH, 150)];
    countLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH/2-20, 30)];
    countLable.textAlignment = NSTextAlignmentCenter;
    payView.backgroundColor = [UIColor whiteColor];
    
    
    priceLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+10, 10, SCREEN_WIDTH/2-20, 30)];
  
    priceLable.textAlignment = NSTextAlignmentCenter;
    
    [payView addSubview:priceLable];
    [payView addSubview:countLable];
    [bgView addSubview:payView];
    

    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(10,40, SCREEN_WIDTH/2-20, 40)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"关闭支付"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(scarePay) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.backgroundColor = UIColorWithRGBA(227, 90,92, 1);
    [payView addSubview:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+10,40, SCREEN_WIDTH/2-20, 40)];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"立即支付"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(surePay) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.backgroundColor = UIColorWithRGBA(227, 90,92, 1);
    [payView addSubview:rightBtn];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _nameArray.count;
}


#pragma mark--- tableViewDelegate 区尾的高度

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 1;
    
}
#pragma mark--- tableViewDelegate cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *NOTIFY = @"cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:NOTIFY];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NOTIFY];
            }
    cell.textLabel.text = _nameArray[indexPath.row];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    UILabel *typeLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-150, 10, 80, 30)];
    typeLable.textAlignment = NSTextAlignmentRight;
    typeLable.textColor = [UIColor orangeColor];
    [cell addSubview:typeLable];
    typeLable.text =[NSString stringWithFormat:@"%@",_priceArray[indexPath.row]];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)scarePay
{
    
    NSString *partner = PartnerID;
    NSString *seller = SellerID;
    NSString *privateKey = PartnerPrivKey;
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = @"这个也就2块钱"; //商品标题
    order.productDescription = @"看看能不能用而已"; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",0.01]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"maimiaogongxue";

    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    ////NSLog(@"orderSpec = %@",orderSpec);

    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            ////NSLog(@"reslut ================ %@",resultDic);
            if ([resultDic[@"resultStatus"]isEqualToString:@"9000"]) {
                 [self ShowProgressHUDwithMessage:@"支付成功"];
            }else
            {
                [self ShowProgressHUDwithMessage:@"支付失败"];
            }
//         ////NSLog(@"reslut ================ %@",resultDic[@"memo"]);
        }];
    }
}

-(void)surePay
{
    PayViewController *sugVC = [[PayViewController alloc]init];
    
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:sugVC];
    [self  presentViewController:nav animated:YES completion:nil];
}

-(void)back
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark -
#pragma mark   ==============产生随机订单号==============


- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

#pragma mark - HUD
- (void)ShowProgressHUDwithMessage:(NSString *)msg
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.dimBackground = NO;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
